package com.miyin.twpull.service.impl;

import com.miyin.twpull.service.TwCommonService;
import com.twitter.clientlib.ApiClient;
import com.twitter.clientlib.TwitterCredentialsBearer;
import com.twitter.clientlib.api.TwitterApi;
import okhttp3.OkHttpClient;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * 推特服务实现类
 */
@Service
public class TwCommonServiceImpl implements TwCommonService {

    private static TwitterApi twitterApiByBearerToken; // TODO 多账户拉取，可能得做成列表

    /**
     * 获取TwitterApi实例对象（单例）
     * @return
     */
    @Override
    public TwitterApi getTwitterApiByBearerToken(){
        if (twitterApiByBearerToken == null) {
            synchronized (TwCommonServiceImpl.class){
                if(twitterApiByBearerToken == null){
                    // 使用不记名令牌
                    TwitterApi apiInstance = new TwitterApi();
                    // 加代理
                    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 1080));
                    ApiClient apiClient = apiInstance.getApiClient();
                    OkHttpClient okHttpClient = apiClient.getHttpClient();
                    OkHttpClient newOkHttpClient = okHttpClient.newBuilder().proxy(proxy).build();
                    apiClient.setHttpClient(newOkHttpClient);

                    apiInstance.setTwitterCredentials(new TwitterCredentialsBearer("AAAAAAAAAAAAAAAAAAAAAEyWcgEAAAAAE7HdQJztDyvox%2FJ5h7P3VD8Lj6w%3DydP5NOVAUFsI1E6rgU8GN1mqM6jWRyZcSuv3MEshiG5Yso1Xfs"));
                    twitterApiByBearerToken = apiInstance;
                }
            }
        }
        return twitterApiByBearerToken;
    }

}
